const express = require('express');
const router = express.Router();
const multer = require('multer');
const dataController = require('../controllers/dataController');
const fileController = require('../controllers/fileController');
const {getPublicKey} = require('../utils/crypto');

// 获取所有数据
router.get('/data', dataController.getAllData);
// 按种类查询
router.get('/data/type', dataController.getDataByType);

// 获取公钥
router.get('/public-key', (req, res) => {
  const publicKey = getPublicKey();
  res.json({ publicKey });
});

router.post('/data/type', dataController.postDataByType);

router.post('/data/calculate',dataController.postCalculateData);

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 设置文件存储目录
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名，避免冲突
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    const ext = path.extname(file.originalname);
    const baseName = path.basename(file.originalname, ext);
    cb(null, `${baseName}-${uniqueSuffix}${ext}`);
  }
});

// 文件过滤 - 可以根据需要调整允许的文件类型
const fileFilter = (req, file, cb) => {
  // 允许所有文件类型，实际应用中可根据需求限制
  cb(null, true);
};

// 配置上传限制：10MB
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
  },
  fileFilter: fileFilter
});

// 上传路由 - 与前端url对应
router.post('/upload', fileController.uploadData);

module.exports = router;
